package com.winway.sixbook.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import com.winway.sixbook.R;
import com.winway.sixbook.service.RecordDataManager;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class ExportDataActivity extends Activity {
	
	private String starttimeString;
	private String endtimeString;
	private String seedtype;
	private String addtime;
	
	ProgressDialog pd=null;
	AlertDialog ad=null,ad1=null;
	AlertDialog.Builder builder=null,builder1=null;
	TextView tv=null;
	Calendar c=Calendar.getInstance();
	
	RecordDataManager recordDataManager ;
	
	TextView exporttitle,exporttitle1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_export_data);
		
		if (recordDataManager == null) {
        	recordDataManager = new RecordDataManager(this);
        	recordDataManager.openDataBase();
        }
		exporttitle = (TextView)findViewById(R.id.exporttitle);
		exporttitle1= (TextView)findViewById(R.id.exporttitle1);
		
		Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        if(null!= bundle ){
        	if(null != bundle.getString("starttime")){
        		starttimeString = bundle.getString("starttime");
        	}
        	if(null != bundle.getString("endtime")){
        		endtimeString = bundle.getString("endtime");
        	}
        	if(null != bundle.getString("seedtype")){
        		seedtype = bundle.getString("seedtype");
        	}
        	if(null != bundle.getString("Addtime")){
        		addtime = bundle.getString("Addtime");
        	}
        }
        
        exporttitle.setText("导出数据时间段："+starttimeString+"至"+endtimeString);
        exporttitle1.setText("导出数据类型："+seedtype);
        
        pd=new ProgressDialog(this);
        tv=new TextView(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage("正在导出功过格到SD卡。。。");
        builder=new AlertDialog.Builder(this);
        builder.setTitle("导出数据");
        tv.setText(Html.fromHtml("<b>警告:</b>  本程序适用于将功过格导出为TXT文本至内存卡。"));
        tv.setMovementMethod(LinkMovementMethod.getInstance());  

		// TODO Auto-generated method stub
		c=Calendar.getInstance();
		pd.show();
		Thread thread=new Thread(new Runnable() {
    		@Override
    		public void run() {
    			// TODO Auto-generated method stub
    			String folderName="/sdcard/";
    			String filename=""+c.get(Calendar.YEAR)+(c.get(Calendar.MONTH)+1)+c.get(Calendar.DAY_OF_MONTH)+c.get(Calendar.HOUR_OF_DAY)+c.get(Calendar.MINUTE)+c.get(Calendar.SECOND)+".txt";
    			System.out.println(filename);
    			File file =null;
    			file=new File(folderName+filename);
    			if(!file.exists()){
    				try {
    					file.createNewFile();
    				} catch (IOException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
    			}
    			FileOutputStream fos=null;
	     
    			try {
    				fos=new FileOutputStream(file, true);
    			} catch (FileNotFoundException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			StringBuffer contentString = new StringBuffer();
    			Cursor groupcursoCursor = recordDataManager.findRecordByTimeandType(starttimeString,endtimeString,seedtype);
    	        if(null != groupcursoCursor){
    	            if(groupcursoCursor.moveToFirst() ){
    	                do{
    	                	String addtime = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_time"));
    	                	String addhour = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_hour"));
    	                	String addmin = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("add_min"));
    	                	String type_name = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("type_name"));
    	                	String type_id = groupcursoCursor.getString(groupcursoCursor.getColumnIndex("type_id"));
    	                	
    	                	contentString.append(addtime+" "+addhour+":"+addmin+"   种子类型："+type_name+"\r\n");
    	                	
    	    				Cursor cursor = recordDataManager.findRecordByTimeslot(addtime,addhour,addmin);
    	    				if(cursor != null ){
	    		               if( cursor.moveToFirst() ){
	    		                   do{
	    		   			        	String newcontent = cursor.getString(cursor.getColumnIndex("content"));
	    		   			        	String contenttype = cursor.getString(cursor.getColumnIndex("contenttype"));
	    		   			        	String newtype_id = cursor.getString(cursor.getColumnIndex("type_id"));
	    		   			        	String titleString = "正    面:";
	    		   			        	if(null != newtype_id && !"".equals(newtype_id)){
	    		   			        		if(Integer.parseInt(newtype_id)==0){
	    	    		   			        	if(null != contenttype && !"".equals(contenttype)){
	    	    		   			        		if(Integer.parseInt(contenttype) == 1){
	    	    		   			        			titleString = "今日最好:";
	    	    		   		                	}else if (Integer.parseInt(contenttype) == 2) {
	    	    		   		                		titleString = "最需改进:";
	    	    		   		        			}else if (Integer.parseInt(contenttype) == 3) {
	    	    		   		        				titleString = "发    愿:";
	    	    		   		        			}
	    	    		   			        	}
	    		   			        		}else{
	    		   			        			if(null != contenttype && !"".equals(contenttype)){
	    	    		   			        		if(Integer.parseInt(contenttype)==1){
	    	    		   			        			titleString = "正    面:";
	    	    		   			        		}else if(Integer.parseInt(contenttype)==2){
	    	    		   			        			titleString = "负    面:";
	    	    		   			        		}else if(Integer.parseInt(contenttype)==3){
	    	    		   			        			titleString = "我    要:";
	    	    		   			        		}
	    	    		   			        	}
	    		   			        		}
	    		   			        	}
	    		   			        	
	    		   			        	contentString.append("  "+titleString+newcontent+"\r\n");
	    		                   }while( cursor.moveToNext());
	    		               }
	    		            }
	    		            cursor.close();
	    		            contentString.append("\r\n");
    	                }while( groupcursoCursor.moveToNext());
    	            }
    	        }
    	        groupcursoCursor.close();
    	        
    	        try {
					fos.write(contentString.toString().getBytes());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    	        
    			try {
    				fos.close();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
	     
	     
    		}
		});
		thread.start();
		pd.dismiss();
		builder.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(ExportDataActivity.this, GridActivity.class);
				Bundle bundle = new Bundle(); 
				bundle.putString("Addtime",addtime);
				intent.putExtras(bundle); 
				startActivity(intent);
				finish();
			}
		});
		builder.setMessage("功过格已经成功导出TXT文本，"+"\n\n"+"文件保存于SD卡根目录。");
		ad=builder.create();
		ad.show();
	
	}
	
	@Override
	protected void onResume() {
		if (recordDataManager == null) {
			recordDataManager = new RecordDataManager(this);
			recordDataManager.openDataBase();
        }
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		if (recordDataManager != null) {
			recordDataManager.closeDataBase();
			recordDataManager = null;
        }
		super.onPause();
	}

}
